<template>
  <div class="filter-section">
    <h4 class="filter-title">请先选择盘点时间：</h4>

    <div class="date-picker-section">
      <el-date-picker 
        v-model="selectedDateRange"
        type="daterange"
        unlink-panels
        range-separator="-"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :shortcuts="dateShortcuts"
        :default-time="defaultDatePickerTime"
        format="YYYY/MM/DD"
        value-format="YYYY-MM-DDTHH:mm:ss.000Z"
      />
      <el-button 
      type="primary" 
      style="margin-left: 15px;"
      @click="exportSelected" 
    >
      批量导出
    </el-button>
    
    </div>

    <h4 class="filter-title">该段时间已盘点设备：</h4>
    <div class="brand-list">
      <el-checkbox-group v-model="selectedInventoried">
        <el-checkbox 
          v-for="brand in inventoriedBrands" 
          :key="'inventoried-'+brand.name"
          :label="brand.name"
          class="brand-item"
        >
          {{ brand.name }} ({{ brand.count }})
        </el-checkbox>
        <el-checkbox 
          v-if="shouldShowAbnormalOption"
          key="showAbnormal"
          label="showAbnormal"
          class="brand-item abnormal-checkbox"
        >
          显示异常设备 ({{ abnormalBrandsCount }})
        </el-checkbox>
      </el-checkbox-group>
    </div>

    <h4 class="filter-title">该段时间未盘点设备：</h4>
    <div class="brand-list">
      <el-checkbox-group v-model="selectedUninventoried">
        <el-checkbox
          v-for="brand in uninventoriedBrands"
          :key="brand.name"
          :label="brand.name"
          class="brand-item"
        >
          {{ brand.name }} ({{ brand.count }})
        </el-checkbox>
      </el-checkbox-group>
    </div>

    <el-table 
      :data="filteredAndPaginatedList" 
      v-loading="loading" 
      header-align="center" 
      fit 
      v-if="filteredAndPaginatedList.length > 0"
    >
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column label="盘点时间" width="160">
        <template #default="{ row }">
          {{ row.time ? formatDate(row.time) : 'N/A' }}
        </template>
      </el-table-column>
      <el-table-column prop="SerialNum" label="SN编号" width="280" />
      <el-table-column prop="EquipmentName" label="设备名称" />
      <el-table-column prop="AssetNum" label="资产编码" />
      <el-table-column v-if="shouldShowAbnormalColumn" prop="AbnormalInfo" label="异常信息" />
      <el-table-column prop="User" label="盘点人" width="80" />
      <el-table-column prop="Location" label="盘点位置" />

      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button size="small" @click="showDetail(row)">操作记录</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[15, 30, 50, 100, 200, 500]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="filteredData.length"
      v-if="filteredAndPaginatedList.length > 0"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from "vue";
import { client } from "../client";
import * as XLSX from 'xlsx';


interface Device {
  EquipmentName: string;
  SerialNum?: string;
  AssetNum?: string;
  time?: Date;
  AbnormalInfo?: string;
  User?: string;
  Location?: string;
  [key: string]: any;
}

interface BrandInfo {
  name: string;
  count: number;
}

// 数据存储
const Assets = ref<Device[]>([]);
const pandianlist = ref<Device[]>([]);
const loading = ref(false);
const selectedUninventoried = ref<string[]>([]);
const selectedInventoried = ref<string[]>([]);
const selectedDateRange = ref<[string, string] | null>(null);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(15);

// 日期处理
const defaultDatePickerTime = ref<[Date, Date]>([
  new Date(2025, 0, 1, 0, 0, 0), // 修正日期初始化
  new Date(2025, 0, 31, 23, 59, 59),
]);

const dateShortcuts = [
  { text: '最近一周', value: () => createDateRange(7) },
  { text: '最近一个月', value: () => createDateRange(30) },
  { text: '最近三个月', value: () => createDateRange(90) },
];

// 数据计算
const inventoriedBrands = computed<BrandInfo[]>(() => {
  if (!selectedDateRange.value) return [];
  const [start, end] = selectedDateRange.value.map(d => new Date(d));

  const countMap = new Map<string, Set<string>>();

  pandianlist.value.forEach(item => {
    const itemTime = new Date(item.time || 0);
    if (itemTime >= start && itemTime <= end) {
      const name = normalizeName(item.EquipmentName);
      if (!countMap.has(name)) {
        countMap.set(name, new Set());
      }
      countMap.get(name)?.add(item.SerialNum || '');
    }
  });

  return Array.from(countMap.entries())
    .map(([name, serialSet]) => ({ name, count: serialSet.size }))
    .sort((a, b) => a.name.localeCompare(b.name));
});

const uninventoriedBrands = computed<BrandInfo[]>(() => {
  if (!selectedDateRange.value) return [];
  const [start, end] = selectedDateRange.value.map(d => new Date(d));
  
  // 获取所有资产的SN号
  const allAssetSNs = new Map<string, Device>();
  Assets.value.forEach(asset => {
    if (asset.SerialNum) {
      allAssetSNs.set(asset.SerialNum, asset);
    }
  });
  
  // 获取已盘点的SN号
  const inventoriedSNs = new Set<string>();
  pandianlist.value.forEach(item => {
    const itemTime = new Date(item.time || 0);
    if (itemTime >= start && itemTime <= end && item.SerialNum) {
      inventoriedSNs.add(item.SerialNum);
    }
  });
  
  // 计算未盘点的设备（按品牌分类）
  const uninventoriedMap = new Map<string, Set<string>>();
  
  // 遍历所有资产，找出未被盘点的
  allAssetSNs.forEach((asset, sn) => {
    if (!inventoriedSNs.has(sn)) {
      const name = normalizeName(asset.EquipmentName);
      if (name) {
        if (!uninventoriedMap.has(name)) {
          uninventoriedMap.set(name, new Set());
        }
        uninventoriedMap.get(name)?.add(sn);
      }
    }
  });
  
  return Array.from(uninventoriedMap.entries())
    .map(([name, serialSet]) => ({
      name,
      count: serialSet.size
    }))
    .filter(b => b.count > 0)
    .sort((a, b) => a.name.localeCompare(b.name));
});

const abnormalBrands = computed<BrandInfo[]>(() => {
  if (!selectedDateRange.value) return [];
  const [start, end] = selectedDateRange.value.map(d => new Date(d));

  const countMap = new Map<string, Set<string>>();

  pandianlist.value.forEach(item => {
    const itemTime = new Date(item.time || 0);
    if (itemTime >= start && itemTime <= end && item.AbnormalInfo) {
      const name = normalizeName(item.EquipmentName);
      if (!countMap.has(name)) {
        countMap.set(name, new Set());
      }
      countMap.get(name)?.add(item.SerialNum || '');
    }
  });

  return Array.from(countMap.entries())
    .map(([name, serialSet]) => ({ name, count: serialSet.size }))
    .sort((a, b) => a.name.localeCompare(b.name));
});

const abnormalBrandsCount = computed(() => {
  return abnormalBrands.value.reduce((total, brand) => total + brand.count, 0);
});

const shouldShowAbnormalOption = computed(() => {
  return selectedDateRange.value !== null && abnormalBrandsCount.value > 0;
});

const shouldShowAbnormalColumn = computed(() => {
  return filteredAndPaginatedList.value.some(item => item.AbnormalInfo);
});

// 数据过滤
const filteredData = computed<Device[]>(() => {
  if (selectedUninventoried.value.length > 0) {
    if (!selectedDateRange.value) return [];
    const [start, end] = selectedDateRange.value.map(d => new Date(d));
    
    // 获取已盘点的SN号
    const inventoriedSNs = new Set<string>();
    pandianlist.value.forEach(item => {
      const itemTime = new Date(item.time || 0);
      if (itemTime >= start && itemTime <= end && item.SerialNum) {
        inventoriedSNs.add(item.SerialNum);
      }
    });
    
    const selectedNames = new Set(
      selectedUninventoried.value.map(normalizeName)
    );
    
    return Assets.value
      .filter(asset => {
        const assetName = normalizeName(asset.EquipmentName);
        // 只显示选中品牌且未被盘点的设备
        return selectedNames.has(assetName) && 
               asset.SerialNum && 
               !inventoriedSNs.has(asset.SerialNum);
      })
      .map(asset => ({
        ...asset,
        time: undefined,
        AbnormalInfo: '未盘点',
        User: '',
        Location: asset.Location || ''
      }));
  }

  if (selectedInventoried.value.length > 0) {
    const selectedNames = new Set(
      selectedInventoried.value.map(normalizeName)
    );

    if (selectedNames.has('showabnormal')) {
      return pandianlist.value.filter(item => {
        const [start, end] = selectedDateRange.value?.map(d => new Date(d)) || [];
        if (!start || !end) return false;
        
        const itemTime = new Date(item.time || 0);
        return itemTime >= start && 
               itemTime <= end && 
               item.AbnormalInfo;
      });
    }

    return pandianlist.value.filter(item => {
      const [start, end] = selectedDateRange.value?.map(d => new Date(d)) || [];
      if (!start || !end) return false;
      
      const itemTime = new Date(item.time || 0);
      const itemName = normalizeName(item.EquipmentName);
      return itemTime >= start && 
             itemTime <= end && 
             selectedNames.has(itemName);
    });
  }

  const [start, end] = selectedDateRange.value?.map(d => new Date(d)) || [];
  return pandianlist.value.filter(item => {
    if (!start || !end) return false;
    const itemTime = new Date(item.time || 0);
    return itemTime >= start && itemTime <= end;
  });
});

const filteredAndPaginatedList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  return filteredData.value.slice(start, start + pageSize.value);
});

// 工具函数
const normalizeName = (name?: string) => {
  return (name?.trim() || '').toLowerCase();
};

const createDateRange = (days: number) => {
  const end = new Date();
  const start = new Date();
  start.setDate(start.getDate() - days);
  return [start.toISOString(), end.toISOString()];
};

const formatDate = (time: string) => {
  const date = new Date(time);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-');
};

// 事件处理
const showDetail = (row: Device) => {
  console.log('查看详情:', row);
};

const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize;
};

const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage;
};

// 数据初始化
onMounted(async () => {
  try {
    const [assetsRes, pandianRes] = await Promise.all([
      client.callApi("GetData", {}),
      client.callApi("pandian/GetData", {})
    ]);
    
    Assets.value = (assetsRes.res.data || [])
      .filter((a: Device) => a.EquipmentName?.trim())
      .map(a => ({ ...a, EquipmentName: normalizeName(a.EquipmentName) }));
      
    pandianlist.value = (pandianRes.res.data || [])
      .filter((item: Device) => item.EquipmentName?.trim())
      .map(item => ({ 
        ...item, 
        EquipmentName: normalizeName(item.EquipmentName) 
      }));
    
  } catch (error) {
    console.error("数据加载失败:", error);
  } finally {
    loading.value = false;
  }
});
const exportSelected = () => {
  // 构建字段映射关系（根据el-table列定义）
  const columnMap = {
    time: { label: '盘点时间', formatter: (v: Date) => v ? formatDate(v) : 'N/A' },
    SerialNum: 'SN编号',
    EquipmentName: '设备名称',
    AssetNum: '资产编码',
    User: '盘点人',
    Location: '盘点位置',
    AbnormalInfo: '异常信息'
  };

  // 获取当前表格展示的完整数据（不分页）
  const exportData = filteredData.value;

  // 构建表头
  const headers = [
    '序号',
    ...Object.values(columnMap)
      .map((v: any) => v.label || v)
      .filter(v => v !== '异常信息' || shouldShowAbnormalColumn.value)
  ];

  // 构建数据行
  const finalMappedRows = exportData.map((row, index) => {
    const rowData: Record<string, any> = { 序号: index + 1 };
    
    Object.entries(columnMap).forEach(([key, config]) => {
      // 处理异常信息列显示逻辑
      if (key === 'AbnormalInfo' && !shouldShowAbnormalColumn.value) return;

      const label = typeof config === 'object' ? config.label : config;
      const formatter = typeof config === 'object' ? config.formatter : null;
      
      rowData[label] = formatter ? formatter(row[key]) : row[key];
    });

    return rowData;
  });

  // 生成Excel
  const worksheet = XLSX.utils.json_to_sheet(finalMappedRows, { header: headers });
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, '盘点数据');
  XLSX.writeFile(workbook, `盘点数据_${new Date().toISOString().slice(0,10)}.xlsx`);
};


// 监听器
watch([selectedDateRange, selectedInventoried, selectedUninventoried], () => {
  currentPage.value = 1;
});
</script>

<style scoped>
.filter-section {
  background: #fff;
}

.filter-title {
  color: #409EFF;
}

.brand-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.brand-item {
  min-width: 160px;
}

.abnormal-checkbox {
  color: red;
}

.date-picker-section {
  margin: 15px 0;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>